package cn.com.xy.sms.sdk.tagsearch;


import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.SysParamEntityManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.util.BaseRunnable;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.ThreadPoolManager;
import cn.com.xy.sms.sdk.util.XyUtil;

/**
 * @author kwb1
 * @version 1.0
 * @created 17-02-2017 16:37:53
 */
public class TagUpdateManager extends BaseRunnable {

    private final String TAG = "TagUpdateManager";
    private final String REQUEST_URL = "tagData";
    private final String KEY_PARAMS_TIME = "tag_update_time";
    /**
     * 更新接口
     */
    public synchronized void updateTagData() {
        ThreadPoolManager.UPDATE_SERVICE.execute(this);
    }

    @Override
    protected boolean inQueryInterval() {
        long time = SysParamEntityManager.getLongParam(KEY_PARAMS_TIME, System.currentTimeMillis(), Constant.getContext());
        long cycleTime = DexUtil
                .getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TAG_SEARCH_UPDATE_CYCLE, Constant.DAY);
        if (time + cycleTime < System.currentTimeMillis())
            return false;
        return true;
    }

    @Override
    public void execute() {
        Map<String, String> queryMap = new HashMap<String, String>();
        queryMap.put("version", TagDbManager.getInstance().getMaxVersion());

        updateTagTableByNet(queryMap, new HashMap<String, String>(), new XyCallBack() {
            @Override
            public void execute(Object... objects) {
                if (objects == null || objects.length <= 1) {
                    LogManager.e(TAG, "Data error");
                    return;
                }
                int flag = (Integer) objects[0];
                if (flag != 3) {
                    LogManager.e(TAG, String.valueOf(objects[1]));
                    return;
                }

                String str = objects[1].toString();
                try {
                    if (!TextUtils.isEmpty(str)) {
                        JSONObject jb = new JSONObject(str);
                        if (jb.has("code")) {
                            if ("90001".equals(jb.optString("code"))) {
                                analysisData(jb);
                                TagCacheManager.getInstance().setUpdateTrue();
                                SysParamEntityManager.setParam(KEY_PARAMS_TIME, (System.currentTimeMillis()) + "");
                            } else {
                                LogManager.e(TAG, str);
                            }
                        }
                    }

                } catch (Throwable t) {
                    LogManager.e(TAG, "execute", t);
                }
            }
        });
    }


    /**
     * 向服务器发起请求
     *
     * @param queryMap
     * @param extend
     * @param callBack
     */
    private void updateTagTableByNet(Map<String, String> queryMap, Map<String, String> extend, final XyCallBack callBack) {

        if (queryMap != null && !queryMap.isEmpty()) {
            String reqeustContent = createReqeustContent(queryMap, extend);
            if (StringUtils.isNull(reqeustContent)) {
                XyUtil.doXycallBackResult(callBack, new Object[]{Integer.valueOf(-10), "reqeustContent null"});
            } else {
                try {
                    NetUtil.executeServiceHttpRequest(REQUEST_URL, reqeustContent, extend, callBack);
                } catch (Throwable var6) {
                    LogManager.e("XIAOYUAN", "TagUpdateManager updateTagTableByNet error:", var6);
                    XyUtil.doXycallBackResult(callBack, new Object[]{Integer.valueOf(-11), var6.getMessage()});
                }
            }
        } else {
            XyUtil.doXycallBackResult(callBack, new Object[]{Integer.valueOf(-10), "map is null"});
        }
    }

    private static String createReqeustContent(Map<String, String> queryMap, Map<String, String> extend) {
        if (queryMap != null && !queryMap.isEmpty()) {
            try {
                JSONObject e = new JSONObject();
                e.put("version", queryMap.get("version"));
                return e.toString();
            } catch (Throwable var3) {
                LogManager.e("XIAOYUAN", "TagUpdateManager createReqeustContent error:", var3);
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 更新标签，
     *
     * @param jb 数据格式 json
     */
    public void analysisData(JSONObject jb) {
        try {
            if (!jb.has("data")) {
                LogManager.e(TAG, jb.optString("content"));
                return;
            }
            JSONArray jsonArray = jb.optJSONArray("data");
            List<TagSceneIdItem> tagList = new ArrayList<TagSceneIdItem>();
            for (int j = 0; j < jsonArray.length(); j++) {
                JSONObject tagObj = (JSONObject) jsonArray.opt(j);
                tagList.add(getTagFromData(tagObj));
            }
            TagDbManager.getInstance().updateData(tagList);
        } catch (Throwable t) {
            LogManager.e(TAG, "analysisData", t);
        }
    }


    private TagSceneIdItem getTagFromData(JSONObject tagObj) {
        TagSceneIdItem item = new TagSceneIdItem();
        item.setTagId(tagObj.optInt("labelId"));
        item.setTagName(tagObj.optString("labelName"));
        item.setParentTagIds(tagObj.optString("parentLabelIds"));
        item.setSceneIds(tagObj.optString("sceneIds"));
        item.setStatus(tagObj.optInt("status"));
        item.setVersion(tagObj.optString("version"));
        item.setPriority(tagObj.optInt("priority"));
        item.setOftenStatus(tagObj.optInt("oftenStatus"));
        return item;
    }

}